package com.teacher.game.framework.util;

import android.graphics.Color;
import com.teacher.ellio.GameMainActivity;
import com.teacher.game.framework.util.Painter;

import java.util.ArrayList;
import java.util.List;

/**
 * 粒子系统管理器 - 管理和控制多个粒子的生命周期
 * 提供粒子池、发射器和特效预设功能
 * 优化版本：使用高性能对象池和批量操作
 */
public class ParticleSystem {
    
    // 粒子列表和池
    private List<Particle> activeParticles;
    private ParticlePool particlePool;
    
    // 系统参数
    private int maxParticles;
    private boolean enabled;
    
    // 性能优化
    private List<Particle> particlesToRemove; // 待移除粒子列表，避免迭代中修改
    private long lastOptimizationTime;
    private static final long OPTIMIZATION_INTERVAL = 5000; // 5秒优化一次
    
    // 统计信息
    private int frameParticleCount;
    private float averageParticleCount;
    private int frameCount;
    
    /**
     * 构造函数
     * @param maxParticles 最大活跃粒子数
     */
    public ParticleSystem(int maxParticles) {
        this.maxParticles = maxParticles;
        this.enabled = true;
        
        // 初始化列表
        activeParticles = new ArrayList<Particle>(maxParticles);
        particlesToRemove = new ArrayList<Particle>(50); // 预分配移除列表
        
        // 获取粒子池实例
        particlePool = ParticlePool.getInstance();
        
        // 重置统计
        frameParticleCount = 0;
        averageParticleCount = 0;
        frameCount = 0;
        lastOptimizationTime = System.currentTimeMillis();
    }
    
    /**
     * 构造函数
     * @param maxParticles 最大活跃粒子数
     * @param poolSize 对象池大小（兼容旧版本，实际使用单例池）
     */
    public ParticleSystem(int maxParticles, int poolSize) {
        this(maxParticles);
    }
    
    /**
     * 默认构造函数
     */
    public ParticleSystem() {
        this(200); // 默认200个活跃粒子
    }
    
    /**
     * 从对象池获取粒子（优化版本）
     */
    private Particle acquireParticle() {
        return particlePool.acquire();
    }
    
    /**
     * 回收粒子到对象池（优化版本）
     */
    private void recycleParticle(Particle particle) {
        if (particle != null) {
            particlePool.release(particle);
        }
    }
    
    /**
     * 更新粒子系统（高性能版本）
     * @param deltaTime 时间间隔
     */
    public void update(float deltaTime) {
        if (!enabled) return;
        
        // 清空待移除列表
        particlesToRemove.clear();
        
        // 更新所有活跃粒子
        for (int i = 0; i < activeParticles.size(); i++) {
            Particle particle = activeParticles.get(i);
            
            if (particle.isActive()) {
                particle.update(deltaTime);
                
                // 检查粒子是否死亡
                if (!particle.isActive()) {
                    particlesToRemove.add(particle);
                }
            } else {
                // 直接添加到待移除列表
                particlesToRemove.add(particle);
            }
        }
        
        // 批量移除死亡粒子并回收
        for (Particle particle : particlesToRemove) {
            activeParticles.remove(particle);
            recycleParticle(particle);
        }
        
        // 更新统计信息
        updateStatistics();
        
        // 定期优化系统性能
        performPeriodicOptimization();
    }
    
    /**
     * 更新统计信息
     */
    private void updateStatistics() {
        frameCount++;
        frameParticleCount += activeParticles.size();
        
        // 每100帧计算一次平均值
        if (frameCount >= 100) {
            averageParticleCount = (float) frameParticleCount / frameCount;
            frameCount = 0;
            frameParticleCount = 0;
        }
    }
    
    /**
     * 执行周期性优化
     */
    private void performPeriodicOptimization() {
        long currentTime = System.currentTimeMillis();
        
        if (currentTime - lastOptimizationTime >= OPTIMIZATION_INTERVAL) {
            // 检查池是否需要优化
            if (particlePool.needsOptimization()) {
                particlePool.optimizePool();
            }
            
            // 如果平均粒子数很低，可以考虑减少最大粒子数
            if (averageParticleCount > 0 && averageParticleCount < maxParticles * 0.3f) {
                // 适当减少最大粒子数以节省内存
                maxParticles = Math.max((int)(averageParticleCount * 2), 100);
            }
            
            lastOptimizationTime = currentTime;
        }
    }
    
    /**
     * 渲染所有活跃粒子
     * @param painter 绘制器
     */
    public void render(Painter painter) {
        if (!enabled) return;
        
        for (Particle particle : activeParticles) {
            if (particle.isActive()) {
                particle.render(painter);
            }
        }
    }
    
    /**
     * 发射单个粒子（优化版本）
     */
    public void emitParticle(float x, float y, float velX, float velY, float life, 
                           int color, float size) {
        if (!enabled || activeParticles.size() >= maxParticles) {
            return;
        }
        
        Particle particle = acquireParticle();
        if (particle != null) {
            particle.init(x, y, velX, velY, life, color, size);
            activeParticles.add(particle);
        }
    }
    
    /**
     * 发射增强粒子（优化版本）
     */
    public void emitAdvancedParticle(float x, float y, float velX, float velY, float life,
                                   int color, float size, int type, float gravity, float friction) {
        if (!enabled || activeParticles.size() >= maxParticles) {
            return;
        }
        
        Particle particle = acquireParticle();
        if (particle != null) {
            particle.initAdvanced(x, y, velX, velY, life, color, size, type, gravity, friction);
            activeParticles.add(particle);
        }
    }
    
    /**
     * 发射文字粒子（优化版本）
     */
    public void emitTextParticle(float x, float y, float velX, float velY, float life,
                               int color, String text) {
        if (!enabled || activeParticles.size() >= maxParticles) {
            return;
        }
        
        Particle particle = acquireParticle();
        if (particle != null) {
            particle.initTextParticle(x, y, velX, velY, life, color, text);
            activeParticles.add(particle);
        }
    }
    
    // ===== 预设特效方法 =====
    
    /**
     * 跳跃特效 - 脚底火花
     */
    public void createJumpEffect(float x, float y) {
        int particleCount = 8;
        float baseVelocity = 100.0f;
        
        for (int i = 0; i < particleCount; i++) {
            float angle = (float)((i / (float)particleCount) * 2 * Math.PI);
            float velX = (float)Math.cos(angle) * baseVelocity * (0.5f + (float)Math.random() * 0.5f);
            float velY = (float)Math.sin(angle) * baseVelocity * (0.5f + (float)Math.random() * 0.5f);
            
            // 向上偏移速度
            velY -= 50;
            
            int color = Color.rgb(255, 165, 0); // 橙色火花
            float size = 2 + (float)Math.random() * 3;
            float life = 0.3f + (float)Math.random() * 0.5f;
            
            emitAdvancedParticle(x, y, velX, velY, life, color, size, 
                               Particle.TYPE_CIRCLE, 200.0f, 0.95f);
        }
    }
    
    /**
     * 碰撞爆炸特效
     */
    public void createCollisionEffect(float x, float y) {
        int particleCount = 15;
        float baseVelocity = 200.0f;
        
        for (int i = 0; i < particleCount; i++) {
            float angle = (float)((i / (float)particleCount) * 2 * Math.PI);
            float speed = baseVelocity * (0.3f + (float)Math.random() * 0.7f);
            float velX = (float)Math.cos(angle) * speed;
            float velY = (float)Math.sin(angle) * speed;
            
            // 随机颜色 - 红色到黄色
            int red = 255;
            int green = (int)(100 + Math.random() * 155);
            int blue = 0;
            int color = Color.rgb(red, green, blue);
            
            float size = 3 + (float)Math.random() * 4;
            float life = 0.5f + (float)Math.random() * 1.0f;
            
            emitAdvancedParticle(x, y, velX, velY, life, color, size,
                               Particle.TYPE_RECT, 150.0f, 0.92f);
        }
        
        // 添加白色闪光效果
        for (int i = 0; i < 5; i++) {
            float velX = (-50 + (float)Math.random() * 100);
            float velY = (-100 + (float)Math.random() * 50);
            
            emitAdvancedParticle(x, y, velX, velY, 0.3f, Color.WHITE, 8,
                               Particle.TYPE_CIRCLE, 0, 0.9f);
        }
    }
    
    /**
     * 得分特效 - 飞散的分数文字
     */
    public void createScoreEffect(float x, float y, int score) {
        // 主分数文字
        emitTextParticle(x, y, 0, -80, 2.0f, Color.YELLOW, "+" + score);
        
        // 周围的装饰粒子
        int particleCount = 6;
        for (int i = 0; i < particleCount; i++) {
            float angle = (float)((i / (float)particleCount) * 2 * Math.PI);
            float velX = (float)Math.cos(angle) * 60;
            float velY = (float)Math.sin(angle) * 60 - 40; // 向上偏移
            
            int color = Color.rgb(255, 215, 0); // 金黄色
            float size = 2 + (float)Math.random() * 2;
            float life = 1.0f + (float)Math.random() * 0.5f;
            
            emitAdvancedParticle(x + (-10 + (float)Math.random() * 20), 
                               y + (-10 + (float)Math.random() * 20), 
                               velX, velY, life, color, size,
                               Particle.TYPE_CIRCLE, 0, 0.98f);
        }
    }
    
    /**
     * 护盾特效 - 光芒粒子
     */
    public void createShieldEffect(float x, float y, float radius) {
        int particleCount = 12;
        
        for (int i = 0; i < particleCount; i++) {
            float angle = (float)((i / (float)particleCount) * 2 * Math.PI);
            float startX = x + (float)Math.cos(angle) * radius;
            float startY = y + (float)Math.sin(angle) * radius;
            
            // 向外发散
            float velX = (float)Math.cos(angle) * 50;
            float velY = (float)Math.sin(angle) * 50;
            
            int color = Color.rgb(100, 150, 255); // 蓝色光芒
            float size = 3 + (float)Math.random() * 2;
            float life = 0.8f + (float)Math.random() * 0.4f;
            
            emitAdvancedParticle(startX, startY, velX, velY, life, color, size,
                               Particle.TYPE_CIRCLE, 0, 0.96f);
        }
    }
    
    /**
     * 道具收集特效
     */
    public void createPowerUpEffect(float x, float y, int powerUpType) {
        int color;
        switch (powerUpType) {
            case 0: // 金币
                color = Color.YELLOW;
                break;
            case 1: // 护盾
                color = Color.BLUE;
                break;
            case 2: // 双倍得分
                color = Color.GREEN;
                break;
            case 3: // 时间减缓
                color = Color.MAGENTA;
                break;
            default:
                color = Color.WHITE;
        }
        
        int particleCount = 10;
        for (int i = 0; i < particleCount; i++) {
            float angle = (float)((i / (float)particleCount) * 2 * Math.PI);
            float velX = (float)Math.cos(angle) * 80;
            float velY = (float)Math.sin(angle) * 80 - 30;
            
            float size = 2 + (float)Math.random() * 3;
            float life = 1.0f + (float)Math.random() * 0.5f;
            
            emitAdvancedParticle(x, y, velX, velY, life, color, size,
                               Particle.TYPE_CIRCLE, 50.0f, 0.97f);
        }
    }
    
    /**
     * 清除所有粒子（优化版本）
     */
    public void clear() {
        // 批量回收所有活跃粒子
        for (Particle particle : activeParticles) {
            recycleParticle(particle);
        }
        activeParticles.clear();
        particlesToRemove.clear();
    }
    
    /**
     * 启用/禁用粒子系统
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
        if (!enabled) {
            clear();
        }
    }
    
    /**
     * 获取系统统计信息（优化版本）
     */
    public String getStatistics() {
        return String.format("粒子系统 - 活跃: %d/%d, 平均: %.1f, 池: %s", 
                           activeParticles.size(), maxParticles,
                           averageParticleCount,
                           particlePool.getStatistics());
    }
    
    /**
     * 紧急清理（在内存不足时调用）
     */
    public void emergencyCleanup() {
        // 清理生命周期超过一半的粒子
        particlesToRemove.clear();
        
        for (Particle particle : activeParticles) {
            if (particle.getLifeRatio() < 0.6f) {
                particlesToRemove.add(particle);
            }
        }
        
        // 批量移除和回收
        for (Particle particle : particlesToRemove) {
            activeParticles.remove(particle);
            recycleParticle(particle);
        }
        
        // 触发池的紧急回收
        particlePool.emergencyRecycle();
    }
    
    // ===== Getter 方法 =====
    
    public boolean isEnabled() { return enabled; }
    public int getActiveParticleCount() { return activeParticles.size(); }
    public int getMaxParticles() { return maxParticles; }
    public float getAverageParticleCount() { return averageParticleCount; }
    public ParticlePool getParticlePool() { return particlePool; }
    
    /**
     * 获取性能指标
     */
    public String getPerformanceMetrics() {
        return String.format("性能指标 - 活跃粒子: %d, 平均: %.1f, 效率: %.1f%%", 
                           activeParticles.size(), 
                           averageParticleCount,
                           particlePool.getEfficiencyRatio() * 100);
    }
    
    /**
     * 检查系统是否需要优化
     */
    public boolean needsOptimization() {
        return particlePool.needsOptimization() || 
               (averageParticleCount > 0 && averageParticleCount > maxParticles * 0.8f);
    }
}